//
//  XGEssenceTableViewController.m
//  BSBuDeJie
//
//  Created by monkey on 2018/12/10.
//  Copyright © 2018 itcast. All rights reserved.
//

#import "XGEssenceViewController.h"
#import "XGAllTableViewController.h"
#import "XGVideoTableViewController.h"
#import "XGVoiceTableViewController.h"
#import "XGPictureTableViewController.h"
#import "XGWordTableViewController.h"
#import "XGWebViewController.h"

@interface XGEssenceViewController () <UIScrollViewDelegate,XGWebViewControllerDelegate>

/// 标题栏文字数组
@property (nonatomic,strong) NSArray<NSString *> *titleArray;
/// 标题视图
@property (nonatomic,strong) UIView *titleView;
/// 内容视图
@property (nonatomic,strong) UIScrollView *contentScrollView;
/// 标题栏下划线
@property (nonatomic,strong) UIView *underLineView;

/// 上一次选中按钮
@property (nonatomic,weak) UIButton *previousSelectedButton;

@end

@implementation XGEssenceViewController

#pragma mark - 控制器生命周期方法

- (void)loadView
{
    [super loadView];
    
    // 设置视图层次结构
    [self setUpUI];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 添加子控制器
    [self addChildViewControllers];
    // 设置内容滚动视图
    [self setUpContentScrollView];
    // 设置导航栏内容
    [self setUpNavigationItem];
    // 默认显示第一个页面
    [self titleButtonAction:self.titleView.subviews.firstObject];
    
    // 如果点击了广告 进行跳转
    if (self.advertisementWebUrl != nil) {
        XGWebViewController *viewController = [XGWebViewController webViewControllerWithURL:self.advertisementWebUrl];
        viewController.isShowBottomToolbar = NO;
        viewController.delegate = self;
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

#pragma mark - 系统其他方法

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    CGFloat width = self.titleView.width / self.titleArray.count;
    [self.titleView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([view isKindOfClass:[UIButton class]]) {
            view.frame = CGRectMake(idx * width, 0, width, self.titleView.height);
        }
    }];
    
    UIButton *firstButton = self.titleView.subviews.firstObject;
    // ios8之后按钮的titleLabel的大小无法直接获取 只能用titleLabel.intrinsicContentSize获取
    CGFloat underLineWidth = firstButton.titleLabel.intrinsicContentSize.width + 10;
    CGFloat underLineHeight = 3;
    self.underLineView.frame = CGRectMake((firstButton.width - underLineWidth) / 2, self.titleView.height - underLineHeight, underLineWidth, underLineHeight);
}

#pragma mark - 事件监听

// 标题按钮被点击
- (void)titleButtonAction:(UIButton *)button
{
    if (button == self.previousSelectedButton) {
        return;
    }
    
    // 取消上一次按钮选中
    self.previousSelectedButton.selected = NO;
    // 当前按钮为选中状态
    button.selected = YES;
    // 当前按钮为选中按钮
    self.previousSelectedButton = button;
    
    [UIView animateWithDuration:0.5 animations:^{
        // 偏移到指定的页面
        CGPoint offset = self.contentScrollView.contentOffset;
        offset.x = button.tag * SCREEN_WIDTH;
        self.contentScrollView.contentOffset = offset;
        // 滚动下划线
        self.underLineView.width = button.titleLabel.intrinsicContentSize.width + 10;
        self.underLineView.centerX = button.centerX;
    } completion:^(BOOL finished) {
        [self addChildViewWithIndex:button.tag];
    }];
}

#pragma mark - 内部其他私有方法

- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.contentScrollView];
    [self.view addSubview:self.titleView];
    
    self.titleView.frame = CGRectMake(0, kStatusBarHeight + kNavigationBarHeight, self.view.width, kHomeTitleViewHeight);
    self.contentScrollView.frame = self.view.bounds;
}

- (void)setUpContentScrollView
{
    // 设置代理
    self.contentScrollView.delegate = self;
    // 设置滚动范围
    self.contentScrollView.contentSize = CGSizeMake(self.childViewControllers.count * SCREEN_WIDTH, 0);
    // 取消导航栏下scrollView默认64偏移
    self.contentScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    self.contentScrollView.bounces = NO;
    self.contentScrollView.showsHorizontalScrollIndicator = NO;
    self.contentScrollView.pagingEnabled = YES;
}

// 设置导航栏
- (void)setUpNavigationItem
{
    UIButton *leftButton = [UIButton buttonWithImageName:@"nav_item_game_icon" highlightedImageName:@"nav_item_game_click_icon" target:nil action:nil];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MainTitle"]];
    self.navigationItem.titleView = imageView;
    
    UIButton *rightButton = [UIButton buttonWithImageName:@"navigationButtonRandom" highlightedImageName:@"navigationButtonRandomClick" target:nil action:nil];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

// 添加子控制器
- (void)addChildViewControllers
{
    NSArray<Class> *childViewControllerClassArray = @[[XGAllTableViewController class],
          [XGVideoTableViewController class],
          [XGVoiceTableViewController class],
          [XGPictureTableViewController class],
          [XGWordTableViewController class]];
    
    for (Class childViewControllerClass in childViewControllerClassArray) {
        [self addChildViewController:[[childViewControllerClass alloc] init]];
    }
}

// 添加子视图
- (void)addChildViewWithIndex:(NSUInteger)index
{
    // 显示对应的页面
    UIViewController *viewController = self.childViewControllers[index];
    if (viewController.isViewLoaded) {
        // 如果已经加载过了 不添加
        return;
    } else {
        viewController.view.frame = CGRectMake(index * SCREEN_WIDTH, 0, self.contentScrollView.width, self.contentScrollView.height);
        viewController.view.tag = index;
        [self.contentScrollView addSubview:viewController.view];
    }
}

#pragma mark - UIScrollViewDelegate

// scrollView停止减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 根据偏移量 选择对应的标题按钮
    NSInteger index = scrollView.contentOffset.x / self.view.width;
    UIButton *button = self.titleView.subviews[index];
    [self titleButtonAction:button];
}

#pragma mark - XGWebViewControllerDelegate

- (void)webViewControllerGoBackAction:(XGWebViewController *)webViewController
{
    [webViewController.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 懒加载

- (NSArray<NSString *> *)titleArray
{
    if (_titleArray == nil) {
        _titleArray = @[@"全部",@"视频",@"声音",@"图片",@"段子"];
    }
    
    return _titleArray;
}

- (UIView *)titleView
{
    if (_titleView == nil) {
        _titleView = [[UIView alloc] init];
        _titleView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
        [self.titleArray enumerateObjectsUsingBlock:^(NSString * _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *button = [UIButton buttonWithTitle:title fontSize:18 titleColor:[UIColor darkGrayColor] target:self action:@selector(titleButtonAction:)];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            button.tag = idx;
            [self->_titleView addSubview:button];
        }];
        
        [_titleView addSubview:self.underLineView];
    }
    
    return _titleView;
}

- (UIScrollView *)contentScrollView
{
    if (_contentScrollView == nil) {
        _contentScrollView = [[UIScrollView alloc] init];
        _contentScrollView.backgroundColor = [UIColor whiteColor];
    }
    
    return _contentScrollView;
}

- (UIView *)underLineView
{
    if (_underLineView == nil) {
        _underLineView = [[UIView alloc] init];
        _underLineView.backgroundColor = [UIColor redColor];
    }
    
    return _underLineView;
}

@end
